package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "菜品管理")
@RestController
@RequestMapping("admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("page")
    @ApiOperation("菜品分页查询")
    public Result page(DishPageQueryDTO dishPageQueryDTO) {
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result insert(@RequestBody DishDTO dishDTO) {
        dishService.insert(dishDTO);
        //新增菜品后 需要清楚redis缓存 保证数据的统一性
        cleanRedis("dish_"+dishDTO.getCategoryId());
        return Result.success();
    }

    @GetMapping("list")
    @ApiOperation("根据分类id查询菜品")
    public Result list(Long categoryId) {
        List<DishVO> list = dishService.list(categoryId);
        return Result.success(list);
    }

    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result delete(@RequestParam List<Long> ids) {
        dishService.delete(ids);
        //删除菜品后 需要清楚redis缓存 保证数据的统一性
        //第一种方法精确删除 使用遍历的方式
//       ids.forEach(id->redisTemplate.delete("dish_"+id));
        //第二种方法删除全部的缓存区
        cleanRedis("dish_*");
        return Result.success();

    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO) {
        dishService.update(dishDTO);
        //修改菜品后 需要清楚redis缓存 保证数据的统一性
       cleanRedis("dish_*");
        return Result.success();
    }

    @GetMapping("{id}")
    @ApiOperation("根据id查询菜品")
    public Result getByid(@PathVariable Long id) {
        DishVO list = dishService.getByid(id);
        return Result.success(list);
    }

    @PostMapping("status/{status}")
    @ApiOperation("修改菜品状态起售停售")
    public Result status(@PathVariable Integer status, Long id) {
        dishService.status(status, id);
        //修改菜品状态后 需要清楚redis缓存 保证数据的统一性
        cleanRedis("dish_*");
        return Result.success();
    }

    //将redis缓存清除操作抽取成一个公共方法
    public void    cleanRedis(String key) {
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);
    }

}
